package com.sharecar.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

public class ServiceUtil {
	public static java.sql.Date javaDateToSqlDate(Date date) {
		return new java.sql.Date(date.getTime());
	}

	/**
	 * Serialize object into byte array.
	 * @param obj the object going to be serialized.
	 * @return byte array the obj serialized into.
	 */
	public static byte[] serializeObjectIntoByteArray(Object obj) {
		byte[] buffer;

		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(obj);
			oos.flush();
			buffer = baos.toByteArray();
			oos.close();
			baos.close();

			return buffer;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 *  deserialize the byte array into a object..
	 * @param array the array going to be deserialized.
	 * @return the object deserialized..
	 */
	public static Object deserializeByteArrayIntoObject(byte[] array) {
		Object obj;
		try {
			ByteArrayInputStream baio = new ByteArrayInputStream(array);
			ObjectInputStream ois = new ObjectInputStream(baio);
			obj = ois.readObject();
			ois.close();
			baio.close();

			return obj;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
}
